package org.lightmtv.interceptors;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.lightcommons.web.auth.AuthManager;
import org.lightmtv.annotation.Secure;
import org.lightmtv.response.Response;
import org.lightmtv.response.TemplateResponse;

public class SecureInterceptor implements MethodInterceptor{
	
	public Object invoke(MethodInvocation invocation) throws Throwable {
		if(invokeAble(invocation.getMethod(), invocation.getThis())){
			return invocation.proceed();
		}else{
			Secure typeSecure = invocation.getThis().getClass().getAnnotation(Secure.class);
			Secure methodSecure = invocation.getMethod().getAnnotation(Secure.class);
			List<String> requires = new ArrayList<String>();
			if(typeSecure!=null)
				requires.add(typeSecure.value());
			if(methodSecure != null)
				requires.add(methodSecure.value());
			if(AuthManager.hasLogin())
				return showFobbiden(requires);
			else
				return showUnauthorized();
		}
	}

	private boolean invokeAble(Method method,Object action){
		Secure typeSecure = action.getClass().getAnnotation(Secure.class);
		Secure methodSecure = method.getAnnotation(Secure.class);
		return invokeAble(typeSecure) && invokeAble(methodSecure);
	}
	
	private boolean invokeAble(Secure secure){
		return secure==null || AuthManager.has(secure.value());
	}
	
	private Response showFobbiden(List<String> requires){
		return new TemplateResponse("403.html").put("requires", requires);
		//		return new Redirect(GlobalContext.getRequest().getContextPath()+"/"+GlobalContext.getSettings().getProperty(PAGE_LOGIN));
	}
	
	private Response showUnauthorized(){
		return new TemplateResponse("401.html");
//		return new Redirect(GlobalContext.getRequest().getContextPath()+"/"+GlobalContext.getSettings().getProperty(PAGE_DENIED));
	}
}
